import { ref, computed, onMounted, unref, watch } from 'vue'
// var elementResizeDetectorMaker = require('element-resize-detector')
export default function useKeyboard(props, emit) {
  const contentRef = ref(null)
  const content = ref(props.value || '')

  const sendable = computed(() => {
    return content.value !== ''
  })

  watch(() => props.value, (newV) => {
    console.log('newV:', newV)
    if (content.value !== newV) {
      content.value = newV
    }
  })

  onMounted(() => {
    // listenToEditorDivContent()
    // const config = { childList: true }

    // const callback = (mutationsList) => {
    //   // console.log(mutationsList)
    //   mutationsList.forEach((item, index) => {
    //     console.log(item)
    //   })
    //   // console.log(contentRef.value.innerHTML)
    // }
    // // 创建一个链接到回调函数的观察者实例
    // var observer = new MutationObserver(callback)
    // // 开始观察已配置突变的目标节点
    // observer.observe(contentRef.value, config)
  })

  // function listenToEditorDivContent() {
  //   var erd = elementResizeDetectorMaker()
  //   erd.listenTo(contentRef.value, function(element) {
  //     console.log(element)
  //   })
  // }

  const getContent = computed(() => {
    const ret = content.value
    console.log(ret)
    return ret
  })

  let keyCodeList = []

  async function handleKeydown(ev) {
    const oEvent = ev || event
    // 13 enter , 17 ctrl
    if ([13, 17].indexOf(oEvent.keyCode) > -1 && keyCodeList.indexOf(oEvent.keyCode) < 0) {
      if (oEvent.preventDefault) oEvent.preventDefault()
      else window.event.returnValue = false
      keyCodeList.push(oEvent.keyCode)
    }
    if (keyCodeList.indexOf(13) > -1) { // enter
      if (keyCodeList.indexOf(17) > -1) { // ctrl
        content.value += '\n'
        keyCodeList = []
      } else {
        handleSend()
        keyCodeList = []
      }
    }
  }

  function handlChange() {
    emit('change', content.value)
  }

  function handleSend() {
    if (!unref(sendable)) return
    emit('send', content.value)
  }

  async function handleKeyUp(ev) {
    const oEvent = ev || event
    // 13 enter , 17 ctrl
    if ([13, 17].indexOf(oEvent.keyCode) > -1 && keyCodeList.indexOf(oEvent.keyCode) < 0) {
      if (oEvent.preventDefault) oEvent.preventDefault()
      else window.event.returnValue = false
      keyCodeList.push(oEvent.keyCode)
    }
    keyCodeList = []
  }

  return {
    contentRef,
    content,
    getContent,
    sendable,
    handleKeydown,
    handleKeyUp,
    handlChange,
    handleSend
  }
}
